﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SklepISI.Core.Interfaces;
using SklepISI.Core.Models;
using SklepISI.Web.Models;

namespace SklepISI.Web.Controllers
{
    [Authorize]
    public class CartController : Controller
    {
        private IProductRepository _productsRepository;

        public CartController(IProductRepository productsRepository)
        {
            _productsRepository = productsRepository;
        }

        private CartSessionModel Cart
        {
            get
            {
                if (Session["StoredCart"] == null)
                {
                    var newCart = new CartSessionModel();
                    Session["StoredCart"] = newCart;
                }
                return Session["StoredCart"] as CartSessionModel;
            }
        }

        public JsonResult ClearCard()
        {
            Session["StoredCart"] = null;

            return Json("Cart Cleared", JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddToCart(int id)
        {
            if (Cart.Products.ContainsKey(id))
                Cart.Products[id] = Cart.Products[id] + 1;
            else
                Cart.Products.Add(id, 1);
            var product = _productsRepository.GetProduct(id);
            var count = Cart.Products.ContainsKey(id) ? Cart.Products[id] : 0;
            return
                Json(
                    new
                        {
                            Success = true,
                            Count = count,
                            TotalProductPrice = String.Format("{0:C}", count * product.Price),
                            TotalCartPrice = String.Format("{0:C}", CountTotalPrice())
                        });
        }

        public JsonResult RemovePermanent(int id)
        {
            var product = _productsRepository.GetProduct(id);
            if (Cart.Products.ContainsKey(id))
            {
                Cart.Products.Remove(id);
            }
            var count = Cart.Products.ContainsKey(id) ? Cart.Products[id] : 0;
            return Json(new
            {
                Success = true,
                Count = count,
                TotalProductPrice = String.Format("{0:C}", count * product.Price),
                TotalCartPrice = String.Format("{0:C}", CountTotalPrice())
            });
        }


        public JsonResult RemoveFromCart(int id)
        {
            var product = _productsRepository.GetProduct(id);
            if (Cart.Products.ContainsKey(id))
            {
                if (Cart.Products[id] == 1)
                    Cart.Products.Remove(id);
                else if (Cart.Products[id] > 0)
                    Cart.Products[id] = Cart.Products[id] - 1;
                var count = Cart.Products.ContainsKey(id) ? Cart.Products[id] : 0;
                return Json(new
                {
                    Success = true,
                    Count = count,
                    TotalProductPrice = String.Format("{0:C}", count * product.Price),
                    TotalCartPrice = String.Format("{0:C}", CountTotalPrice())
                });
            }
            else
            {
                var count = Cart.Products.ContainsKey(id) ? Cart.Products[id] : 0;
                return Json(new
                {
                    Success = false,
                    Count = count,
                    TotalProductPrice = String.Format("{0:C}", count * product.Price),
                    TotalCartPrice = String.Format("{0:C}", CountTotalPrice())
                });
            }

        }

        private decimal CountTotalPrice()
        {
            return CountAmount(PrepareOrderedProducts().Products);
        }

        public ActionResult CartPreview()
        {
            var dupa = Request.IsAjaxRequest();
            var model = new CartPreviewViewModel();

            model.Order = PrepareOrderedProducts();
            model.Amount = CountAmount(model.Order.Products);

            return View(model);
        }

        private OrderModel PrepareOrderedProducts()
        {
            var order = new OrderModel();
            order.Products = new Collection<OrderContentModel>();

            var products = _productsRepository.GetProducts();

            foreach (var p in Cart.Products)
            {
                var product = products.Where(x => x.ProductId == p.Key).FirstOrDefault();

                if (product != null)
                {
                    OrderContentModel content = new OrderContentModel { Price = product.Price, Product = product, Quantity = p.Value };
                    order.Products.Add(content);
                }
            }
            return order;
        }

        private decimal CountAmount(ICollection<OrderContentModel> products)
        {
            decimal amount = 0;

            foreach (var p in products)
            {
                amount += p.Price * p.Quantity;
            }

            return amount;
        }

    }
}
